<?php

namespace app\admin\controller\bonus;

use app\common\controller\Backend;
use app\common\model\general\LihuaCity;
use app\common\model\LihuaBonus;

/**
 * 红包管理
 *
 * @icon fa fa-circle-o
 */
class Bonus extends Backend
{
    protected $cityLimit = true;

    /**
     * LihuaBonus模型对象
     * @var LihuaBonus
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new LihuaBonus;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where('status', '<', 2)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('status', '<', 2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $cityArr = LihuaCity::getCityArr();
            $list    = collection($list)->toArray();
            foreach ($list as $k => $v) {
                $list[$k]['city_name'] = isset($cityArr[$v['city_id']]) ? $cityArr[$v['city_id']] : '';
            }

            $result  = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = 0) {
        if ($ids) {
            $where['id'] = $ids;
            if ($this->auth->city_id > 0) $where['city_id'] = $this->auth->city_id;
            $this->model->where($where)->setField('status', 2);
            $this->success();
        }
        $this->error();
    }

    /**
     * 选择当前城市的红包
     */
    public function sel($city_id = 0) {
        $where = [];
        if($city_id==0) $city_id =  $this->auth->city_id;
        if ($city_id > 0) $where['city_id'] = $city_id;
        $list = $this->model->where($where)->where('status', '<', 2)->select();
        $res = [
            'list' => $list,
            'total'=> count($list)
        ];
        return json($res);
    }

}
